'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: response.py
* @Time: 2025/9/17
* @All Rights Reserve By Brtc
'''
from dataclasses import dataclass
from typing import Any, Union, Generator
from attrs import field
from flask import jsonify, Response as FlaskResponse, stream_with_context

from .http_code import HttpCode


@dataclass
class Response:
    """基于http 接口响应格式参数"""
    code:HttpCode=HttpCode.SUCCESS
    message:str=""
    data:Any = field(default=dict)

def json(data:Response):
    #flask json 数据组装
    return jsonify(data), 200


def success_json(data:Any=None):
    return json(Response(code=HttpCode.SUCCESS, message="",data=data))


def fail_json(data:Any=None):
    return json(Response(code=HttpCode.FAIL, message="",data=data))


def validate_error_json(data:Any=None):
    return json(Response(code=HttpCode.VALIDATE_ERROR, message="",data=data))


def message(code:HttpCode, message:str):
    return json(Response(code=code, message=message,data={}))


def success_message(msg:str=""):
    return message(code=HttpCode.SUCCESS, message=msg)


def fail_message(msg:str=""):
    return message(code=HttpCode.FAIL, message=msg)


def not_found_message(msg:str=""):
    return message(code=HttpCode.NOT_FOUND, message=msg)


def unauthorized_message(msg:str=""):
    return message(code=HttpCode.UNAUTHORIZED, message=msg)


def forbidden_message(msg:str=""):
    return message(code=HttpCode.FORBIDDEN, message=msg)



def compact_generate_response(response:Union[Response, Generator])->FlaskResponse:
    """统一合并处理https 的块输出以及流式事件响应"""
    #1、检测下是否为块输出
    if isinstance(response, Response):
        return json(response)
    else:
        #2、response格式为flask 生成器,代表本地响应需要执行的流式事件输出
            def generate()->Generator:
                """构建generate 函数， 流式的从response 中获取数据"""
                yield from response
            return FlaskResponse(
                stream_with_context(generate()),
                status=200,
                mimetype="text/event-stream"
            )
